package com.loongtech.bi.action.monitor;

import com.loongtech.bi.action.authManagement.ResultData;
import com.loongtech.bi.entity.POJO.Page;
import com.loongtech.bi.entity.POJO.PojoMonitorResult;
import com.loongtech.bi.manager.system.BiMonitorConfigManager;
import com.loongtech.bi.manager.system.BiMonitorResultManager;
import com.loongtech.bi.manager.system.BiPlatformManager;
import com.loongtech.core.util.RetCode;
import com.loongtech.core.util.Time;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Author: yuri
 * Description: 监控结果展示
 * Date: 16:42 2017/5/17
 */

@RestController
@Scope("prototype")
@RequestMapping("/monitorresult")
public class MonitorResultAction {
    @Resource
    private BiMonitorResultManager biMonitorResultManager;
    @Resource
    private BiMonitorConfigManager biMonitorConfigManager;

    @RequestMapping(value = "list.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<?> searchByCriteria(@RequestParam Integer curPage, @RequestParam Integer pageSize, @RequestParam(value = "dateStart", required = false) String dateStart, @RequestParam (value = "dateEnd", required = false) String dateEnd) {
        Date start;
        Date end;
        if (dateStart == null) {
            start = new Date(Time.getBeginningOfDay(Time.currentTime()));
        } else {
            start = Time.formatDate(dateStart, "yyyy-MM-dd HH:mm:ss");
        }
        if (dateEnd == null) {
            end = new Date(Time.getEndOfDay(Time.currentTime()));
        } else {
            end = Time.formatDate(dateEnd, "yyyy-MM-dd HH:mm:ss");
        }
        Page<List<PojoMonitorResult>> res;
        try {
           res = biMonitorResultManager.queryByCriteria(curPage, pageSize, start, end);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
        for (PojoMonitorResult pojoMonitorResult : res.getData()) {
            Integer id = pojoMonitorResult.getJobId();
            String description = biMonitorConfigManager.get(id) == null ? id + "" : id + "-" + biMonitorConfigManager.get(id).getDescription();
            pojoMonitorResult.setDescription(description);
            pojoMonitorResult.setServerName( BiPlatformManager.getServerNameById(pojoMonitorResult.getServerId()));
        }
        return new ResultData<>(RetCode.eSuccess.getErrorcode(), res);
    }
}
